package controllers

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"time"

	"soccerStar/models"
	"soccerStar/services"
)

type AdminController struct {
	Service services.SuperstarService
}

func (c *AdminController) Get(ctx *gin.Context) {
	datalist := c.Service.GetAll()
	// set the model and render the view template.
	ctx.HTML(http.StatusOK, "adminIndex.html", gin.H{
		"Title":    "管理后台",
		"Datalist": datalist,
	})
	/*
		return mvc.View{
			Name: "admin/indexIndex.html",
			Data: iris.Map{
				"Title":    "管理后台",
				"Datalist": datalist,
			},
			Layout: "admin/adminLayout.html", // 不要跟前端的layout混用
		}
	*/
}

func (c *AdminController) GetEdit(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Param("id"))
	//id, err := c.Ctx.URLParamInt("id")
	var data *models.StarInfo
	if err == nil {
		data = c.Service.Get(id)
	} else {
		data = &models.StarInfo{
			Id: 0,
		}
	}
	//fmt.Println(id, data)
	// set the model and render the view template.
	ctx.HTML(http.StatusOK, "adminEdit.html", gin.H{
		"Title": "管理后台",
		"info":  data,
	})
	/*
		return mvc.View{
			Name: "admin/adminEdit.html",
			Data: iris.Map{
				"Title": "管理后台",
				"info":  data,
			},
			Layout: "admin/adminLayout.html", // 不要跟前端的layout混用
		}
	*/
}

func (c *AdminController) PostSave(ctx *gin.Context) {
	Id, err1 := strconv.Atoi(ctx.PostForm("id"))
	Height, err2 := strconv.Atoi(ctx.PostForm("height"))
	Weight, err3 := strconv.Atoi(ctx.PostForm("weight"))
	if err1 != nil || err2 != nil || err3 != nil {
		log.Fatalf("id or Height or Weight have error,err1=", err1, " err2=", err2, " err3=", err3)
	}
	info := models.StarInfo{
		Id:           Id,
		NameZh:       ctx.PostForm("name_zh"),
		NameEn:       ctx.PostForm("name_en"),
		Avatar:       ctx.PostForm("avatar"),
		Birthday:     ctx.PostForm("birthday"),
		Height:       Height,
		Weight:       Weight,
		Club:         ctx.PostForm("club"),
		Jersy:        ctx.PostForm("jersy"),
		Country:      ctx.PostForm("country"),
		Birthaddress: ctx.PostForm("birthaddress"),
		Feature:      ctx.PostForm("feature"),
		Moreinfo:     ctx.PostForm("moreinfo"),
	}
	//fmt.Printf("%v\n", info)
	if info.Id > 0 {
		info.SysUpdated = int(time.Now().Unix())
		c.Service.Update(&info, []string{"name_zh", "name_en", "avatar",
			"birthday", "height", "weight", "club", "jersy", "coutry",
			"birthaddress", "feature", "moreinfo", "sys_updated"})
	} else {
		info.SysCreated = int(time.Now().Unix())
		c.Service.Create(&info)
	}
	ctx.Redirect(http.StatusMovedPermanently, "/admin/")
}

func (c *AdminController) GetDelete(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	//id, err := c.Ctx.URLParamInt("id")
	if err == nil {
		c.Service.Delete(id)
	}
	ctx.Redirect(http.StatusMovedPermanently, "/admin/")
}
